<template>
  <el-dialog title="Add Shift" :visible.sync="dialogVisible" width="35%" :before-close="handleClose">
    <el-form :model="shiftInfo" label-width="30%" :rules="formRules" ref="formRef">
      <el-form-item label="Department" prop="department">
        <el-select v-model="shiftInfo.department" placeholder="select" class="select" @change="getDepartStaff(shiftInfo.department)">
          <el-option
            v-for="item in department"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Staff" prop="staff">
        <el-select v-model="shiftInfo.staff" placeholder="select" class="select">
          <el-option
            v-for="item in staffData"
            :key="item.number"
            :label="item.name"
            :value="item.number">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Abbreviation" prop="nickName">
        <el-input
          class="select"
          v-model="shiftInfo.nickName"
          placeholder="No more than three letters">
        </el-input>
      </el-form-item>
      <el-form-item label="Role" prop="role">
        <el-select v-model="shiftInfo.role" placeholder="select" class="select">
          <!-- <el-option value="Manager Assistent"></el-option>
          <el-option value="Manager"></el-option> -->
          <el-option
            v-for="item in roleList"
            :key="item.uid"
            :label="item.rolename"
            :value="item.rolename"
          ></el-option>
        </el-select>
        <el-button type="text" class="link-button" @click="roleVisible = true">Set Role</el-button>
      </el-form-item>
      <el-form-item label="Time" prop="time">
        <el-time-picker
          class="select"
          is-range
          v-model="shiftInfo.time"
          range-separator="-"
          start-placeholder="startTime"
          end-placeholder="endTime"
          placeholder="select time range"
          format="HH:mm"
          value-format="HH:mm">
        </el-time-picker>
      </el-form-item>
      <el-form-item label="Cycle" prop="cycle">
        <el-select v-model="shiftInfo.cycle" placeholder="select" class="select">
          <el-option label="Never" value="Never"></el-option>
          <el-option label="Everyday" value="Everyday"></el-option>
          <el-option label="Every Week on" value="Everyweek"></el-option>
          <el-option label="Every Workdays" value="Everyweekday"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="button">
      <el-button @click="handleClose">Cancel</el-button>
      <div style="display: inline-block; width: 50px"></div>
      <el-button type="primary" @click="handleSubmit">Submit</el-button>
    </div>
    <el-dialog class="inner" title="Edit Role" :visible.sync="roleVisible" width="25%" append-to-body>
      <div class="edit-role">
        <div class="title">
          <span>Role</span>
        </div>
        <div
          class="role-list"
          v-for="(item,index) in roleList"
          :key="index">
          <span>{{item.rolename}}</span>
          <span style="float:right">
            <i class="el-icon-delete iconfont" @click="deleteRole(item.uid)"></i>
          </span>
        </div>
        <el-input
          class="input-new-role"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else size="small" @click="showInput">+</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="roleVisible=false">confirm</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
export default {
  name: "addShift",
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    dayTime: {
      type: String,
      default: '',
    }
  },
  data(){
    let validStaff = (rule, value, callback) => {
      if(value && !this.shiftInfo.department){
        this.shiftInfo.staff = '';
        return callback(new Error('Select a department first'));
      }else {
        callback();
      }
    }
    return {
      dialogVisible: this.isShow,
      date: this.dayTime,
      user: {},
      department: [],
      staffData: [],
      roleVisible: false,
      inputVisible: false,
      inputValue: '',
      roleList: [],
      shiftInfo: {
        department: '',
        nickName: '',
        staff: '',
        role: '',
        time: '',
        cycle: '',
      },
      formRules: {
        department: [
          { required: true, message: 'Department is required', trigger: 'change' },
        ],
        staff: [
          { required: true, message: 'Staff is required', trigger: 'change' },
          { validator: validStaff, trigger: 'change' }
        ],
        nickName: [
          { required: true, message: 'nickName is required', trigger: 'blur' },
        ],
        role: [
          { required: true, message: 'Role is required', trigger: 'change' },
        ],
        time: [
          { required: true, message: 'Time is required', trigger: 'blur' },
        ],
        cycle: [
          { required: true, message: 'Cycle is required', trigger: 'change' },
        ]
      }
    }
  },
  watch: {
    isShow(val){
      this.dialogVisible = val;
    },
    dayTime(val){
      this.date = val;
    },
  },
  created(){
    this.getRole();
  },
  mounted(){
    this.user = JSON.parse(sessionStorage.getItem('user'));
    this.staffData = JSON.parse(sessionStorage.getItem('staffData'));
    if(this.staffData === null){
      this.getAllStaff();
    }
    this.department = JSON.parse(sessionStorage.getItem('department'));
    if(this.department === null){
      this.getAllDepartment();
    }
  },
  methods: {
    getRole() {
      const _this = this;
      _this.$api.arrange.getRole().then(res => {
        if(res.data.code === 2000){
          _this.roleList = res.data.data;
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    deleteRole(uid){
      const _this = this;
      _this.$api.arrange.deleteRole({
        uid: uid
      }).then(res => {
        if(res.data.code === 2000){
          _this.getRole();
          _this.$message.success("Delete success");
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const _this = this;
      let inputValue = this.inputValue;
      if(inputValue){
        _this.$api.arrange.addRole({
          rolename: inputValue
        }).then(res => {
          if(res.data.code === 2000){
            _this.getRole();
            _this.$message.success("Add success");
          } else {
            _this.$message.error(res.data.message);
          }
        }).catch(err => {
          console.log(err);
        })
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleClose() {
      const _this = this;
      _this.dialogVisible = false;
      this.staffData = JSON.parse(sessionStorage.getItem('staffData'));
      _this.$emit('handleClose');
      //清空表单和表单验证error
      _this.$nextTick(() => {
        _this.$refs.formRef.resetFields();
      })
      // 清空表单
      Object.keys(_this.shiftInfo).forEach(((value) => {
        _this.shiftInfo[value] = '';
      }))
    },
    handleSubmit(){
      const _this=this;
      _this.$refs.formRef.validate(valid => {
        if(!valid) return;
        _this.$api.arrange.addArrange({
          number: _this.shiftInfo.staff,
          department_id: _this.shiftInfo.department,
          start_time: _this.shiftInfo.time[0],
          finish_time: _this.shiftInfo.time[1],
          manager_number: _this.user.number,
          date: _this.date,
          cycle: _this.shiftInfo.cycle,
          role: _this.shiftInfo.role,
          abbrev: _this.shiftInfo.nickName,
        }).then(res => {
          if(res.data.code === 2000){
            _this.$message.success('Add success');
            _this.handleClose();
          }else {
            _this.$message.error(res.data.message);
          }
        }).catch(err => {
          console.log(err);
        })
      })
    },
    getAllStaff(){
      const _this = this
      _this.$api.staff.getAllStaff().then(res => {
        if (res.data.code === 2000) {
          _this.staffData = res.data.data;
          // _this.sortPosition(_this.staffData)
          sessionStorage.setItem('staffData',JSON.stringify(_this.staffData));
          _this.managerData = _this.staffData.filter((item) => {
            return item.position != 'Staff'
          })
          sessionStorage.setItem('managerData',JSON.stringify(_this.managerData));
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    getAllDepartment() {
      const _this = this
      _this.$api.department.getAllDepartment().then(res => {
        if (res.data.code === 2000) {
          _this.department = res.data.data;
          sessionStorage.setItem('department',JSON.stringify(_this.department));
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    getDepartStaff(index){
      const _this = this;
      // var department_id = _this.deDetail[index].id;
      this.shiftInfo.staff = '';
      _this.$api.staff.getDepartStaff({
        department_id: index,
      }).then(res => {
        if(res.data.code === 2000){
          _this.staffData = res.data.data;
        }else{
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
  }
}
</script>

<style scoped lang="less">
  .select {
    width: 205px;
  }
  .input {
    width: 205px;
  }
  .button {
    text-align: center;
    padding-top: 15px;
  }
  .link-button {
    margin-left: 10px;
    text-decoration: underline;
  }
  .inner {
    /deep/ .el-dialog__body{
      padding-top: 10px;
      padding-left: 40px;
      padding-bottom: 0px;
    }
  }
  .edit-role{
    width: 95%;
    .title{
      line-height: 30px;
      font-size: 16px;
      font-weight: 600;
    }
    .role-list {
      line-height: 30px;
      font-size: 14px;
      .el-icon-delete {
        margin-right: 10px;
        font-size: 18px;
        color: rgba(246,119,28,0.9);
        vertical-align: middle;
        cursor: pointer;
      }
    }
  }
  .input-new-role {
    width: 150px;
    // margin-left: 10px;
    // margin-bottom: 10px;
    vertical-align: bottom;
  }
</style>
